<?php
// +----------------------------------------------------------------------
// | PHP [ JUST YOU ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2017 http://www.jyphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: FlyingPig <flyingpigfp@163.com>
// +----------------------------------------------------------------------

namespace App\Http\Controllers;


use App\Common\HttpClient;
use App\Common\Tool;
use App\Exceptions\ApiException;
use App\Logic\MiGuLogic;
use App\Model\MallConf\TicketMallConf;
use App\Model\User\User;
use Illuminate\Support\Facades\DB;

class BuyTicket extends Base
{

    public function handle()
    {
        $object = TicketMallConf::where('id', $this->param['id'])->where('status', 1)->first(['price', 'ticket']);
        if (empty($object)) {
            throw new ApiException('商品不存在');
        }
        $user = User::where('id', $this->uid)->where('diamonds', '>=', $object->price)->first(['id','diamonds','room_ticket']);
        if (empty($user)) {
            throw new ApiException('钻石不足,无法兑换');
        }
        $user->diamonds = $user->diamonds - $object->price;
        $user->room_ticket   = $user->room_ticket + $object->ticket;
        DB::beginTransaction();
        try {
            if (!$user->save()) {
                throw new ApiException('兑换失败');
            }
            DB::table('t_user_diamonds_rec')->insert([
                'uid' => $this->uid,
                'num' => -$object->price,
                'source' => '钻石兑换房卡',
                'comment' => 'diamonds:' . $object->price . '-' . 'room_card:' . $object->ticket
            ]);
            DB::commit();
            return $this->returnData([
                'currentDiamonds' => $user->diamonds,
                'currentRoomCards' => $user->room_ticket
            ]);
        } catch (\Exception $exception) {
            DB::rollBack();
            throw new ApiException('兑换失败'.$exception->getMessage());
        }
    }

}